use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use comp_agent::controller::agent_execute_shell::execute_as_user;
use lazy_static::lazy_static;
use serde_json;
use std::process::Command;
use std::sync::Mutex;

// 为不同操作系统导入适当的函数
#[cfg(target_os = "linux")]
use libc::getuid;

// Windows相关导入已移除，因为我们现在使用sudo权限检查而非UID检查

// 检查是否具有sudo权限
fn has_sudo_permission() -> bool {
    Command::new("sudo")
        .arg("-v")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

// 存储程序启动用户（应该是root用户）
lazy_static! {
    static ref ROOT_USER: Mutex<String> = Mutex::new(String::new());
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 检查是否在Linux系统上运行
    if !cfg!(target_os = "linux") {
        eprintln!("错误: 此程序只能在Linux系统上运行");
        std::process::exit(1);
    }

    // 检查是否具有sudo权限
    if !has_sudo_permission() {
        eprintln!("错误: 程序必须以具有sudo权限的用户运行");
        std::process::exit(1);
    }

    // 存储当前用户名
    {
        let mut root_user = ROOT_USER.lock().unwrap();
        // 获取当前用户名
        let output = Command::new("whoami")
            .output()
            .expect("无法获取当前用户名");
        *root_user = String::from_utf8_lossy(&output.stdout).trim().to_string();
    }

    println!("Comp Agent 服务启动中...");
    println!("监听地址: http://0.0.0.0:8080");

    HttpServer::new(|| {
        App::new()
            .route("/api/execute", web::post().to(execute_handler))
    })
    .bind("0.0.0.0:8080")?
    .run()
    .await
}

// 处理执行脚本的HTTP请求
async fn execute_handler(body: web::Bytes) -> impl Responder {
    // 解析请求体
    let request_body = match String::from_utf8(body.to_vec()) {
        Ok(body) => body,
        Err(e) => {
            return HttpResponse::BadRequest().body(format!("请求体解析失败: {}", e));
        }
    };

    // 解析JSON请求
    let request: Result<serde_json::Value, _> = serde_json::from_str(&request_body);
    let request = match request {
        Ok(req) => req,
        Err(e) => {
            return HttpResponse::BadRequest().body(format!("JSON解析失败: {}", e));
        }
    };

    // 提取目标用户和脚本
    let target_user = match request.get("user") {
        Some(user) => match user.as_str() {
            Some(u) => u,
            None => return HttpResponse::BadRequest().body("用户字段必须是字符串"),
        },
        None => return HttpResponse::BadRequest().body("缺少用户字段"),
    };

    let script = match request.get("script") {
        Some(s) => match s.as_str() {
            Some(script) => script,
            None => return HttpResponse::BadRequest().body("脚本字段必须是字符串"),
        },
        None => return HttpResponse::BadRequest().body("缺少脚本字段"),
    };

    // 提取超时时间（可选）
    let timeout = match request.get("timeout") {
        Some(t) => t.as_u64(),
        None => Some(60), // 默认60秒
    };

    // 执行脚本
    match execute_as_user(target_user, script, timeout) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            let status = output.status.code().unwrap_or(-1);

            let response = serde_json::json!({
                "success": true,
                "status": status,
                "stdout": stdout,
                "stderr": stderr
            });

            HttpResponse::Ok().json(response)
        },
        Err(e) => {
            let response = serde_json::json!(
                {
                    "success": false,
                    "error": e
                }
            );
            HttpResponse::InternalServerError().json(response)
        }
    }
}